{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# TorchMultimodal Tutorial: Finetuning FLAVA\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Multimodal AI has recently become very popular owing to its ubiquitous\nnature, from use cases like image captioning and visual search to more\nrecent applications like image generation from text. **TorchMultimodal\nis a library powered by Pytorch consisting of building blocks and end to\nend examples, aiming to enable and accelerate research in\nmultimodality**.\n\nIn this tutorial, we will demonstrate how to use a **pretrained SoTA\nmodel called** [FLAVA](https://arxiv.org/pdf/2112.04482.pdf)_ **from\nTorchMultimodal library to finetune on a multimodal task i.e. visual\nquestion answering** (VQA). The model consists of two unimodal transformer\nbased encoders for text and image and a multimodal encoder to combine\nthe two embeddings. It is pretrained using contrastive, image text matching and \ntext, image and multimodal masking losses.\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Installation\nWe will use TextVQA dataset and bert tokenizer from HuggingFace for this\ntutorial. So you need to install datasets and transformers in addition to TorchMultimodal.\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>When running this tutorial in Google Colab, install the required packages by\n   creating a new cell and running the following commands:\n\n```\n!pip install torchmultimodal-nightly\n!pip install datasets\n!pip install transformers</p></div>\n```\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Steps \n\n1. Download the HuggingFace dataset to a directory on your computer by running the following command:\n\n```\nwget http://dl.fbaipublicfiles.com/pythia/data/vocab.tar.gz \ntar xf vocab.tar.gz\n```\n   .. note:: \n      If you are running this tutorial in Google Colab, run these commands\n      in a new cell and prepend these commands with an exclamation mark (!)\n\n\n2. For this tutorial, we treat VQA as a classification task where\n   the inputs are images and question (text) and the output is an answer class. \n   So we need to download the vocab file with answer classes and create the answer to\n   label mapping.\n\n   We also load the [textvqa\n   dataset](https://arxiv.org/pdf/1904.08920.pdf)_ containing 34602 training samples\n   (images,questions and answers) from HuggingFace\n\nWe see there are 3997 answer classes including a class representing\nunknown answers.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "with open(\"data/vocabs/answers_textvqa_more_than_1.txt\") as f:\n  vocab = f.readlines()\n\nanswer_to_idx = {}\nfor idx, entry in enumerate(vocab):\n  answer_to_idx[entry.strip(\"\\n\")] = idx\nprint(len(vocab))\nprint(vocab[:5])\n\nfrom datasets import load_dataset\ndataset = load_dataset(\"textvqa\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Lets display a sample entry from the dataset:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np \nidx = 5 \nprint(\"Question: \", dataset[\"train\"][idx][\"question\"]) \nprint(\"Answers: \" ,dataset[\"train\"][idx][\"answers\"])\nim = np.asarray(dataset[\"train\"][idx][\"image\"].resize((500,500)))\nplt.imshow(im)\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "3. Next, we write the transform function to convert the image and text into\nTensors consumable by our model - For images, we use the transforms from\ntorchvision to convert to Tensor and resize to uniform sizes - For text,\nwe tokenize (and pad) them using the BertTokenizer from HuggingFace -\nFor answers (i.e. labels), we take the most frequently occuring answer\nas the label to train with:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\nfrom torchvision import transforms\nfrom collections import defaultdict\nfrom transformers import BertTokenizer\nfrom functools import partial\n\ndef transform(tokenizer, input):\n  batch = {}\n  image_transform = transforms.Compose([transforms.ToTensor(), transforms.Resize([224,224])])\n  image = image_transform(input[\"image\"][0].convert(\"RGB\"))\n  batch[\"image\"] = [image]\n\n  tokenized=tokenizer(input[\"question\"],return_tensors='pt',padding=\"max_length\",max_length=512)\n  batch.update(tokenized)\n\n\n  ans_to_count = defaultdict(int)\n  for ans in input[\"answers\"][0]:\n    ans_to_count[ans] += 1\n  max_value = max(ans_to_count, key=ans_to_count.get)\n  ans_idx = answer_to_idx.get(max_value,0)\n  batch[\"answers\"] = torch.as_tensor([ans_idx])\n  return batch\n\ntokenizer=BertTokenizer.from_pretrained(\"bert-base-uncased\",padding=\"max_length\",max_length=512)\ntransform=partial(transform,tokenizer)\ndataset.set_transform(transform)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "4. Finally, we import the flava_model_for_classification from\ntorchmultimodal. It loads the pretrained flava checkpoint by default and\nincludes a classification head.\n\nThe model forward function passes the image through the visual encoder\nand the question through the text encoder. The image and question\nembeddings are then passed through the multimodal encoder. The final\nembedding corresponding to the CLS token is passed through a MLP head\nwhich finally gives the probability distribution over each possible\nanswers.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torchmultimodal.models.flava.model import flava_model_for_classification\nmodel = flava_model_for_classification(num_classes=len(vocab))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "5. We put together the dataset and model in a toy training loop to\ndemonstrate how to train the model for 3 iterations:\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torch import nn\nBATCH_SIZE = 2\nMAX_STEPS = 3\nfrom torch.utils.data import DataLoader\n\ntrain_dataloader = DataLoader(dataset[\"train\"], batch_size= BATCH_SIZE)\noptimizer = torch.optim.AdamW(model.parameters())\n\n\nepochs = 1\nfor _ in range(epochs):\n  for idx, batch in enumerate(train_dataloader):\n    optimizer.zero_grad()\n    out = model(text = batch[\"input_ids\"], image = batch[\"image\"], labels = batch[\"answers\"])\n    loss = out.loss\n    loss.backward()\n    optimizer.step()\n    print(f\"Loss at step {idx} = {loss}\")\n    if idx > MAX_STEPS-1:\n      break"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Conclusion\n\nThis tutorial introduced the basics around how to finetune on a\nmultimodal task using FLAVA from TorchMultimodal. Please also check out\nother examples from the library like\n[MDETR](https://github.com/facebookresearch/multimodal/tree/main/torchmultimodal/models/mdetr)_\nwhich is a multimodal model for object detection and\n[Omnivore](https://github.com/facebookresearch/multimodal/blob/main/torchmultimodal/models/omnivore.py)_\nwhich is multitask model spanning image, video and 3d classification.\n\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.4"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}